Mybatis foreach 批量操作

文章目录
  1. 1. mybatis foreach 遍历传递进来的集合
    1. 1.1. mapper 接口
    2. 1.2. mapper.xml
  2. 2. foreach 批量插入数据
    1. 2.1. mapper 接口
    2. 2.2. mapper.xml
  3. 3. 执行多条 SQL 批量插入数据
    1. 3.1. mapper.xml

mybatis foreach 遍历传递进来的集合

mapper 接口

List<Employee> getEmpsByConditions(@Param("list") List<Integer> idList);

mapper.xml

<!-- 注意返回的数据类型是集合中保存的数据类型 Employee-->
<select id="getEmpsByConditions" resultType="com.jas.mybatis.bean.Employee">
SELECT * FROM t_employee WHERE id IN
<!--
collection:指定要遍历的集合
item:取出当前集合中元素,赋给 item 中的值
separator:遍历出的多个元素之间用什么分隔符分隔开
open:遍历集合前用什么字符进行拼接
close:遍历集合后用什么字符进行拼接

在 foreach 标签中还有一个属性 index,
遍历集合的时候 index 表示的是当前元素的索引,item 对应索引中的值
遍历 map 的时候 index 表示的是当前 map 中的 key,item 是 key 对应的 value
-->
<foreach collection="list" item="item" separator="," open="(" close=")">
#{item}
</foreach>
</select>

foreach 批量插入数据

mapper 接口

Integer addEmpsByList(@Param("list") List<Employee> list);

mapper.xml

<insert id="addEmpsByList" parameterType="com.mybatis.bean.Employee">
INSERT INTO t_employee(username, gender, email) VALUES
<foreach collection="list" item="item" separator=",">
(#{item.username}, #{item.gender}, #{item.email})
</foreach>
</insert>

执行多条 SQL 批量插入数据

mapper.xml

<insert id="addEmpsByList" parameterType="com.mybatis.bean.Employee">
<!--
每插入一条数据就执行一次 SQL,中间用";"分隔开
-->
<foreach collection="list" item="item" separator=";">
INSERT INTO t_employee(username, gender, email) VALUES
(#{item.username}, #{item.gender}, #{item.email})
</foreach>
</insert>

MySql 默认的情况下是不支持使用;分隔开多条 SQL 进行执行的,程序会报错org.springframework.jdbc.BadSqlGrammarException,Mybatic 批量操作必须加上参数 &allowMultiQueries=true

community.jdbc.url=jdbc:mysql://172.25.28.8:3306/jr_community?createDatabaseIfNotExist=true&amp;characterEncoding=utf-8&amp;useUnicode=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
community.jdbc.username=
community.jdbc.password=

参数意思是允许多查询